package com.ciwong.epaper.ui;

import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.bean.RfTokenInfo;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.epaper.util.DisplayUtils;
import com.ciwong.epaper.util.EJumpManager;
import com.ciwong.epaper.util.FeedbackUtil;
import com.ciwong.epaper.util.HttpRequest;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.volley.BaseRequest;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.utils.BaseConstants;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/4/7.
 */

public class GuideActivity extends FragmentActivity implements View.OnClickListener {
    private ViewPager viewPager;
    private List<Fragment> fragments;
    private LinearLayout ll_gray_dots;
    private ImageView iv_red_dot;
    private Button btn_gotomain;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(setView());
        findViews();
        initEvent();
        init();
    }


    protected int setView() {
        return R.layout.activity_guide;
    }

    /**
     *
     */
    protected void findViews() {

        btn_gotomain = (Button) findViewById(R.id.btn_gotomain);
        viewPager = (ViewPager) findViewById(R.id.view_pager);
        ll_gray_dots = (LinearLayout) findViewById(R.id.ll_gray_dots);
        iv_red_dot = (ImageView) findViewById(R.id.iv_red_dot);
    }

    /**
     * 点的间距
     **/
    private int mDotDistance;

    protected void initEvent() {
        btn_gotomain.setOnClickListener(this);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) iv_red_dot.getLayoutParams();
//                int newRedLeftMargin = (int) (position * mDotDistance + positionOffset * mDotDistance);
//                params.leftMargin = newRedLeftMargin;
//                iv_red_dot.setLayoutParams(params);
            }

            @Override
            public void onPageSelected(int position) {
                try {
                    if (position == fragments.size() - 1) {
                        btn_gotomain.setVisibility(View.VISIBLE);
                    } else {
                        btn_gotomain.setVisibility(View.GONE);
                    }
                    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) iv_red_dot.getLayoutParams();
                    int newRedLeftMargin = (position * mDotDistance);
                    params.leftMargin = newRedLeftMargin;
                    iv_red_dot.setLayoutParams(params);
                } catch (Exception e) {
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }


    protected void init() {
        fragments = new ArrayList<Fragment>();
//       fragments.add(new GuideFragment0());
        fragments.add(new GuideFragment1());
        fragments.add(new GuideFragment2());
        fragments.add(new GuideFragment3());
        getFragmentManager();
        if (fragments.size() == 1) {
            btn_gotomain.setVisibility(View.VISIBLE);
        }
        viewPager.setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) {
            @Override
            public int getCount() {
                return fragments.size();
            }

            @Override
            public Fragment getItem(int position) {
                return fragments.get(position);
            }
        });
        initdots();
    }

    private void initdots() {
        for (int i = 0; i < fragments.size(); i++) {
            ImageView grayDot = new ImageView(this);
            // 显示灰色效果
            grayDot.setBackgroundResource(R.drawable.shap_gray_dot);
            // 添加进线性布局
            ll_gray_dots.addView(grayDot);
            if (i > 0) {
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, // 宽
                        LinearLayout.LayoutParams.WRAP_CONTENT);// 高
                params.leftMargin = DisplayUtils.dip2px(this, 12);
                grayDot.setLayoutParams(params);
            }
        }
        // 需要监听onLayout执行完毕 如果该方法不执行 未执行完 getLeft..都为0
        // OnGlobalLayoutListener监听布局完毕
        if (ll_gray_dots != null && ll_gray_dots.getChildCount() >= 2) {
            ll_gray_dots.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                @Override
                public void onGlobalLayout() {
                    // 获取任意两个点
                    // getChildAt获取布局上面的子控件
                    int xDot2 = ll_gray_dots.getChildAt(1).getLeft();
                    int xDot1 = ll_gray_dots.getChildAt(0).getLeft();
                    mDotDistance = xDot2 - xDot1;
                    // 使用该监听器 已经获取了点的间距
                    ll_gray_dots.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
            });
        }

    }

    private BaseRequest.VerifyInfo verifyInfo;

    private void checkToken() {
        try {
            verifyInfo = HttpRequest.getVerifyInfo();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (null != verifyInfo) {
            String accessToken = verifyInfo.getAccessToken();
            String refreshToken = verifyInfo.getRefreshToken();
            if (!TextUtils.isEmpty(accessToken) && !TextUtils.isEmpty(refreshToken)) {
                Log.i("lqi", "accessToken" + accessToken + "refreshToken" + refreshToken);
                updateUserToken(refreshToken);
            } else {
                goToMainActivity(false);
            }
        } else {
            goToMainActivity(false);
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_gotomain) {
            if (EApplication.PLATFORM_ENV == EApplication.PLATFORM_PAD) {
                EJumpManager.jumpToMain(0, this);
                finish();
            } else {
                checkToken();
            }

        }
    }

    private void goToMainActivity(boolean isLogin) {
        if (isLogin) {//用户已经登录
            EJumpManager.jumpToMain(0, this);
        } else {//用户未登录
            EJumpManager.jumpToLogin(0, this);
        }
        finish();
    }


    private void updateUserToken(String rfToken) {
        MeDao.getInstance().updateUserToken(rfToken, new BaseCallBack() {
            @Override
            public void success(Object data) {
                RfTokenInfo rfTokenInfo = (RfTokenInfo) data;
                String accessToken = rfTokenInfo.getAccessToken();
                String refreshToken = rfTokenInfo.getRefreshToken();
                String expires = rfTokenInfo.getRefreshToken();
                if (null != verifyInfo) {
                    verifyInfo.setAccessToken(accessToken);
                    verifyInfo.setRefreshToken(refreshToken);
                    verifyInfo.setExpiresIn(expires);
                    HttpRequest.setVerifyInfo(verifyInfo);
                    try {
                        CWSys.setSharedSerializable(BaseConstants.SHARE_KEY_VERITIFY_INFO,
                                verifyInfo);
                        //上报登录信息
                        FeedbackUtil.getInstance().asyncUploadUserLogin();
                        goToMainActivity(true);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    goToMainActivity(false);
                }
            }

            @Override
            public void failed(int errorCode, Object data) {
                goToMainActivity(false);
            }

            @Override
            public void failed(Object data) {
                goToMainActivity(true);
            }
        });
    }
}
